package service

import (
	"teacher-helper/dao"
	"teacher-helper/models"
	"teacher-helper/models/request"
)

func AddOneClass(Class models.SysClass) error {
	return dao.DB.Create(&Class).Error
}

func GetClassList(queryInfo request.QueryInfo, user *request.CustomClaims) (Classs []models.SysClass, total int, err error) {
	if queryInfo == (request.QueryInfo{}){
		err = dao.DB.Where("id in (?)", user.ClassIds).Preload("Counselor").Preload("Grade").Preload("Major").Find(&Classs).Count(&total).Error
		return
	}
	if queryInfo.Query == "" {
		if err = dao.DB.Model(&models.SysClass{}).Where("id in (?)", user.ClassIds).Count(&total).Error; err != nil {
			return
		}
		err = dao.DB.Where("id in (?)", user.ClassIds).Limit(queryInfo.PageSize).Offset((queryInfo.PageNum - 1) * queryInfo.PageSize).Preload("Counselor").Preload("Grade").Preload("Major").Find(&Classs).Error
	} else {
		if err = dao.DB.Model(&models.SysClass{}).Where("name like ? and id in (?)", queryInfo.Query+"%", user.ClassIds).Count(&total).Error; err != nil {
			return
		}
		err = dao.DB.Where("name like ? and id in (?)", queryInfo.Query+"%", user.ClassIds).Limit(queryInfo.PageSize).Offset((queryInfo.PageNum - 1) * queryInfo.PageSize).Preload("Counselor").Preload("Grade").Preload("Major").Find(&Classs).Error
	}
	return
}

func GetMajorClass(major_id int, grade_name string) (classList []models.SysClass, err error)  {
	err = dao.DB.Model(&models.SysClass{}).Joins("left join sys_grades on sys_grades.id = sys_classes.grade_id").Where("major_id = ? and sys_grades.name = ?", major_id, grade_name).Find(&classList).Error
	return
}

func GetClassMajorList(id int) (cls_major_list []int, err error) {
	var major models.SysMajor
	err = dao.DB.Select("department_id").Where(&models.SysMajor{ID:id}).First(&major).Error
	cls_major_list = []int{major.DepartmentID, id}
	return
}

func UpdateClass(Class models.SysClass) error {
	return dao.DB.Save(&Class).Error
}

func DeleteClass(id int) error {
	return dao.DB.Where("id = ?", id).Delete(&models.SysClass{}).Error
}

